import { defineStore } from 'pinia';
import { getNotReadMessage } from "@/api/message";
import { updateViewedRegistrations, updateViewedReplies } from "@/api/message";
import { SUCCESS } from "@/core/constants/HttpStatus";
import { ref } from "vue"
import { ElMessage } from "element-plus";

export const useMessageStore = defineStore('message', () => {
    //未读消息状态：有（true） 没有（false）
    const hasUnreadMessages = ref(false);
    //获取未读消息状态
    const getNewMessageState = async () => {
        try {
            const res = await getNotReadMessage();
            const { code, msg, data } = res.data;
            if (code != SUCCESS) {
                throw new Error(msg);
            }
            hasUnreadMessages.value = data;
        } catch (e) {
            ElMessage.error(e.message || "获取信息失败");
        }
    }

    //有未读消息
    const updateHasUnreadMessages = async () => {
        hasUnreadMessages.value = true;
    }
    //退出登录
    const updateNoneUnreadMessages = async () => {
        hasUnreadMessages.value = false;
    }

    //修改消息状态为已读---回复我的
    const sendReplyState = async () => {
        try {
            const res = await updateViewedReplies();
            const { code, msg } = res.data;
            if (code != SUCCESS) {
                throw new Error(msg);
            }
            getNewMessageState();
        } catch (e) {
            ElMessage.error(e.message || "更新信息失败");
        }
    }
    //修改消息状态为已读---组队申请
    const sendApplyState = async () => {
        try {
            const res = await updateViewedRegistrations();
            const { code, msg } = res.data;
            if (code != SUCCESS) {
                throw new Error(msg);
            }
            getNewMessageState();
        } catch (e) {
            ElMessage.error(e.message || "更新信息失败");
        }
    }
    return {
        getNewMessageState, hasUnreadMessages, updateHasUnreadMessages,updateNoneUnreadMessages, sendReplyState, sendApplyState
    }
})
